package com.fastfly.domain;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import javax.persistence.Transient;

import com.fastfly.service.FastFlyException;


@Entity
public class Ticket extends BaseEntity {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;		
	
	@ManyToOne(cascade=CascadeType.PERSIST)
	protected Seat seatInDepartureFlight;
	
	@ManyToOne(cascade=CascadeType.PERSIST)
	protected Seat seatInReturnFlight;
	
	@ManyToOne
	protected Reservation reservation;
	
	@Transient
	protected long newSeatDepartureId;  
	
	@Transient
	protected long newSeatReturningId;

	public Ticket() {
		super();		
	}

	public Ticket(Seat seatInDepartureFlight, Seat seatInReturnFlight) {
		super();		
		setSeatInDepartureFlight(seatInDepartureFlight);		
		setSeatInReturnFlight(seatInReturnFlight);		
	}

	public Seat getSeatInDepartureFlight() {
		return seatInDepartureFlight;
	}

	public void setSeatInDepartureFlight(Seat seat) {
		setupSeat(seat, this.seatInDepartureFlight);			
		this.seatInDepartureFlight = seat;		
		newSeatDepartureId = this.seatInDepartureFlight.getId();
	}

	public Seat getSeatInReturnFlight() {
		return seatInReturnFlight;
	}

	public void setSeatInReturnFlight(Seat seat) {
		setupSeat(seat, this.seatInReturnFlight);				
		this.seatInReturnFlight = seat;
		newSeatReturningId = this.seatInReturnFlight.getId();
	}
	
	protected void setupSeat(Seat seat, Seat oldSeat) {
		if (! seat.isAvailable()) {
			throw new FastFlyException("Seat is not available: " + seat.getNumber() + " in flight " + seat.getFlight().getFlightNumber());
		}
		seat.setStatus( Seat.RESERVED_STATUS );
		if ( oldSeat != null) {
			oldSeat.setStatus(Seat.AVAILABLE_STATUS);			
		}	
	}
	
	
	
	@Transient
	public double getPrice() {
		return seatInDepartureFlight.getFlight().getPrice() + seatInReturnFlight.getFlight().getPrice();		
	}

	public Reservation getReservation() {
		return reservation;
	}

	public void setReservation(Reservation reservation) {
		this.reservation = reservation;
	}

	public long getNewSeatDepartureId() {
		return newSeatDepartureId;
	}

	public void setNewSeatDepartureId(long newSeatDepartureId) {
		this.newSeatDepartureId = newSeatDepartureId;
	}

	public long getNewSeatReturningId() {
		return newSeatReturningId;
	}

	public void setNewSeatReturningId(long newSeatReturningId) {
		this.newSeatReturningId = newSeatReturningId;
	}
	
}
